<template>
  <div class="container">
    <NavBar :header-height="headerHeights" @doBack="doBack" title="AI文案生成">
      <div class="right" @click="jumpTopage">剩余<span>{{ remainTimes }}</span>次</div>
    </NavBar>
    <Watermark :content="['内容由AI生成', '仅供参考，自辨合规']" :style="{ height: contentHeight }" />
    <Dialog :show="showDialog" :message="dialogMessage" @onConfirm="jumpTopage" @onCancel="onCancel"></Dialog>
    <div class="content" :style="{ height: contentHeight }" @touchstart="touchCoversation" ref="contentRef">
      <van-pull-refresh v-model="loading" pulling-text="加载中..." loosing-text="释放即可加载..." @refresh="onRefresh"
        :success-text="!finished ? '' : '已经到顶了'" :success-duration="800">
        <div class="history">
          <div class="chat-messages" v-for="(item, index) in sessionHistoryList" :key="index"
            :style="{ padding: item.loading ? '5px 12px 0px 12px' : '' }">
            <div class="pre-line ask-message" v-html="item.query" v-if="[1, 3, 7, 9, 4, 6].includes(item.scene)"></div>
            <DailyRecommend v-if="[1, 3, 7, 9, 4, 6].includes(item.scene)"
              :dailyRecommend="{ title: item.title, screenPlay: item.body, promptId: item.promptId }"
              :title="item.scene == 1 ? '原创内容每日推荐' : '为您生成文案如下'" class="generate-text" :isHistory="true"
              style="margin-bottom: 15px"></DailyRecommend>
          </div>
        </div>
        <Divider :text="sessionHistoryList.length === 0 ? '下拉看看我们的回忆' : '以上是我们的回忆'" :paddingBetween="'0 15px'"
          v-if="showHistory"></Divider>
        <div class="coversation">
          <DailyRecommend :dailyRecommend="dailyRecommend" @doRetry="doRetry($event, '原创内容每日推荐')" :btnType="pageType">
          </DailyRecommend>
          <GuideOptions class="dialog-options" @doChoice="doChoice" style="margin-top: 15px; margin-bottom: 15px">
          </GuideOptions>
          <div class="chat-messages" style="padding: 0">
            <div v-for="(item, index) in dialogData" :key="index"
              :class="[item.isUser ? 'ask-message' : 'answer-message']" :style="{ padding: item.loading ? '15px' : 0 }">
              <img v-if="item.isError" :class="[item.isUser ? 'error-icon' : 'none']" :src="errorIcon"
                @click="doResend(item.content, index)" />
              <div class="pre-line" v-html="item.content" v-if="!item.isDailyRecommend && !item.normal"
                :style="{ padding: item.errorMsg ? '15px' : 0 }"></div>
              <div class="pre-line" v-html="item.content" v-if="item.normal" style="padding: 15px"></div>
              <div class="retry" @click="freeTalkRetry(dialogData[index - 1].content)"
                v-if="!item.isUser && !item.loading && !item.isFirstClassGuidance && !item.isSecondClassGuidance && !item.isDailyRecommend && !item.normal">
                <i class="retry-icon" :class="{ 'rotate-icon': rotating }"></i>重新生成
              </div>
              <GuideOptions v-if="item.isFirstClassGuidance" @doChoice="doChoice" :guidance="firstClassGuidance" />
              <GuideOptions v-if="item.isSecondClassGuidance" @doChoice="doChoice" :guidance="secondClassGuidance" />
              <DailyRecommend v-if="item.isDailyRecommend" :dailyRecommend="item.content"
                @doRetry="doRetry($event, '为您生成文案如下', dialogData[index - 1].content)" title="为您生成文案如下"
                class="generate-text" :btnType="pageType"></DailyRecommend>
              <img class="ai-loading" v-if="item.loading" :src="AI_loading" />
            </div>
          </div>
        </div>
      </van-pull-refresh>
    </div>
    <div class="input-area" :class="[{ 'keyboard-show': keyboardShow }]" v-if="iosClient" ref="inputRef">
      <div class="input-wrapper" @click="onInput" :style="{ width: getFocus ? '85%' : '' }">
        <!-- <TypeSwitch @switch="changePageType($event)" :focus="pageType" /> -->
        <van-field v-model="message" rows="1" autosize type="textarea" @blur="onBlur" ref="textareaRef"
          @input="handleInput" @focus="onFocus" />
        <span class="placeholder">{{ placeholder }}</span>
      </div>
      <i :class="[getFocus ? 'send' : '']" @click="sendMsg('', '', '')"></i>
    </div>
    <div class="input-area" :class="[{ 'keyboard-show': keyboardShow }]" v-else>
      <div class="input-wrapper" @click="onInput" :style="{ width: keyboardShow ? '85%' : '' }">
        <van-field v-model="message" rows="1" autosize type="textarea" @blur="onBlur" ref="textareaRef"
          @input="handleInput" @focus="onFocus" />
        <!-- <TypeSwitch @switch="changePageType($event)" :focus="pageType" /> -->
        <span class="placeholder">{{ placeholder }}</span>
      </div>
      <i :class="[keyboardShow ? 'send' : '']" @click="sendMsg('', '', '')"></i>
    </div>
  </div>
  <Loading v-if="pageLoading"></Loading>
</template>

<script setup>
import { ref, onMounted, watch, onActivated } from "vue";
import { useRouter } from "vue-router";
import { closeWindow } from "@/../utils/bridge";
import { headerHeight, isAndroid } from "@/../utils";
import { getUrlParams } from "../utils";
import { getAccountInfos } from "@/../utils";
import { reqDailyRecommend, reqBotResult, reqFreeTalk, reqGuideOptions, reqGuideResult, reqSessionHistory } from "../api/aigc.js";
import { reqPointsInfo } from "../api/index.js";
import { Toast } from "vant";
import Loading from "../components/Loading.vue";
import NavBar from "../components/NewNavbar.vue";
import Dialog from "../components/Dialog.vue";
import Watermark from "../components/Watermark.vue";
import DailyRecommend from "../components/AIGC/DailyRecommend.vue";
import GuideOptions from "../components/AIGC/GuideOptions.vue";
import TypeSwitch from "../components/AIGC/TypeSwitch.vue";
import Divider from "../components/AIGC/Divider.vue";
import AI_loading from "../asset/icons/AI_loading.gif";
import errorIcon from "../asset/icons/failed@3x.png";
const pageLoading = ref(false);

// 定义头部及会话内容高度
const headerHeights = ref("44px");
if (headerHeight) {
  headerHeights.value = headerHeight();
}
const contentHeight = ref("100vh");
contentHeight.value = `calc(100vh - ${headerHeights.value} - 100px - 30px)`; // 30px是预估底部安全区padding
const doBack = (fromPage) => {
  console.log(">>>> fromPage >>>>", fromPage);
  if (fromPage) {
    closeWindow();
  } else {
    history.back();
  }
};

// 获取用户权益数据
const router = useRouter();
const remainTimes = ref(0);
const dialogMessage = ref("你的AI脚本生成权益不足，先去兑换权益吧~");
const showDialog = ref(false);
const getPointsInfo = async () => {
  pageLoading.value = true;
  const { code, data, msg } = await reqPointsInfo(userId.value, getUrlParams("benefitId"));
  if (code == 0 && data.result) {
    pageLoading.value = false;
    remainTimes.value = data.result.availableCounts;
  } else {
    Toast(`获取权益兑换数据失败\ncode${code} ${msg} `);
  }
};
const onCancel = () => {
  showDialog.value = false;
};

// 点击跳转至兑换页
const jumpTopage = () => {
  onCancel();
  router.push(`/exchangeBenefit?title=aiScript&benefitId=${getUrlParams("benefitId")}`);
};

// 缓存状态更新数据时调用
onActivated(async () => {
  await getPointsInfo();
  setTimeout(() => {
    contentRef.value.scrollTop = contentRef.value.scrollHeight;
  }, 300);
});

// 获取dom
const textareaRef = ref(null);
const contentRef = ref(null);

// 历史记录下拉加载
const loading = ref(false);
const finished = ref(false);
const pageNum = ref(1);
const sessionHistoryList = ref([]);
const onRefresh = async () => {
  let preHeight = contentRef.value.scrollHeight;
  await getHistory();
  contentRef.value.scrollTop = contentRef.value.scrollHeight - preHeight - 400; // 调整滚动条位置
};

const getHistory = async () => {
  let scene = pageType.value == 1 || 2 ? 'smartTopic' : '';   //  设置获取历史记录的场景
  let pageNumber = sessionHistoryList.length === 0 ? 1 : pageNum.value++;
  console.log(">>>> scene当前场景 >>>>", scene);
  const { code, data, msg } = await reqSessionHistory(userId.value, pageNumber, endTime.value, scene);
  if (code == 0 && data.result) {
    sessionHistoryList.value.unshift(...data.result.history.reverse());
    loading.value = false;
    if (data.result.history.length === 0) {
      finished.value = true;
    }
  } else {
    Toast(`获取聊天记录失败\ncode${code} ${msg}`);
    finished.value = true;
    loading.value = false;
  }
};

// 会话部分（引导、自由对话）
const dialogData = ref([]);
const userMessage = ref("");
// 引导选项部分
const originGuidance = ref([]);
const firstClassGuidance = ref([]);
const secondClassGuidance = ref([]);
const doChoice = (choice) => {
  if (isAnswering.value) {
    Toast("正在回答中，请稍后发送");
    return;
  } else {
    sendMsg(choice);
  }
};
const staticGuidence = ["我需要引导", "我知道自己想写什么主题"];
// 仿异步发送消息
const sendMsg = (choice, resendMsg, regenerate) => {
  // 响应中不能继续发送
  if (isAnswering.value) {
    Toast("正在回答中，请稍后发送");
    return;
  }
  // 发送空白(仅ios做此校验)
  if (iosClient.value && !choice && !getFocus.value && !resendMsg && !regenerate) {
    return;
  }
  // 引导生成文案及静态引导的重新生成
  if (choice || staticGuidence.includes(regenerate)) {
    if (regenerate) {
      choice = regenerate;
    }
    switch (choice) {
      case "我知道自己想写什么主题":
        dialogData.value.push({
          content: "我知道自己想写什么主题",
          isUser: true,
        });
        setTimeout(() => {
          contentRef.value.scrollTop = contentRef.value.scrollHeight; // 获取焦点后会话部分滚动到最底部
        }, 100);
        setTimeout(() => {
          dialogData.value.push({
            content: "描述您想写的主题，例如：“写一个呼吁大家重视养老，及时规划养老的脚本”",
            normal: true,
          });
        }, 300);
        setTimeout(() => {
          contentRef.value.scrollTop = contentRef.value.scrollHeight;
        }, 300);
        return;
      case "我需要引导":
        if (!regenerate) {
          dialogData.value.push({
            content: "我需要引导",
            isUser: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
        }
        // 调引导接口，获取引导选项
        setTimeout(async () => {
          const { code, data, msg } = await reqGuideOptions(userId.value);
          if (code == 0 && data.result) {
            originGuidance.value = data.result.guidance;
            firstClassGuidance.value = data.result.guidance.map((item) => item.name);
            console.log(">>>> firstClassGuidance.value >>>>", firstClassGuidance.value);
            if (regenerate) {
              dialogData.value.pop();
              setTimeout(() => {
                contentRef.value.scrollTop = contentRef.value.scrollHeight;
              }, 100);
            }
            setTimeout(() => {
              dialogData.value.push({
                isFirstClassGuidance: true,
              });
            }, 500);
            setTimeout(() => {
              contentRef.value.scrollTop = contentRef.value.scrollHeight; // 获取焦点后会话部分滚动到最底部
            }, 500);
          }
          if (code != 0) {
            Toast(`获取引导选项失败\ncode${code} ${msg}`);
            if (!regenerate) {
              dialogData.value.push({
                content: "引导选项获取失败",
                errorMsg: true,
              });
              setTimeout(() => {
                contentRef.value.scrollTop = contentRef.value.scrollHeight;
              }, 100);
            }
          }
        }, 100);
        return;
      default:
        if (firstClassGuidance.value.includes(choice)) {
          dialogData.value.push({
            content: choice,
            isUser: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
          // 获取二级引导
          if (originGuidance.value.find((item) => item.name === choice).children) {
            secondClassGuidance.value = originGuidance.value.find((item) => item.name === choice).children.map((itm) => itm.name);
            console.log(">>>> secondClassGuidance.value >>>>", secondClassGuidance.value);
            setTimeout(() => {
              dialogData.value.push({
                isSecondClassGuidance: true,
              });
            }, 1000);
            setTimeout(() => {
              contentRef.value.scrollTop = contentRef.value.scrollHeight;
            }, 1000);
          } else {
            setTimeout(async () => {
              const { code, data, msg } = await reqGuideResult(userId.value, 7, choice);
              if (code == 0 && data.result) {
                promptId.value = data.result.promptId;
                polling(getGenerateResult); // 获取promptId，轮训文案生成接口
                setTimeout(() => {
                  dialogData.value.push({
                    content: "",
                    loading: true,
                  });
                }, 100);
                setTimeout(() => {
                  contentRef.value.scrollTop = contentRef.value.scrollHeight;
                }, 100);
              }
              if (data.result == "" || code != 0) {
                Toast(`一级引导获取文案失败\ncode${code} ${data.msg}`);
                dialogData.value.push({
                  content: "一级引导选项获取文案失败" + data.msg,
                  errorMsg: true,
                });
                setTimeout(() => {
                  contentRef.value.scrollTop = contentRef.value.scrollHeight;
                }, 100);
              }
            }, 100);
          }
        } else {
          if (remainTimes.value < 1) {
            showDialog.value = true; // 用户可用当前权益的次数不足
            return;
          }
          setTimeout(async () => {
            const { code, data, msg } = await reqGuideResult(userId.value, 7, choice);
            if (code == 0 && data.result) {
              promptId.value = data.result.promptId;
              polling(getGenerateResult); // 获取promptId，轮训文案生成接口
              dialogData.value.push({
                content: choice,
                isUser: true,
              });
              setTimeout(() => {
                contentRef.value.scrollTop = contentRef.value.scrollHeight;
              }, 100);
              setTimeout(() => {
                dialogData.value.push({
                  content: "",
                  loading: true,
                });
              }, 100);
              setTimeout(() => {
                contentRef.value.scrollTop = contentRef.value.scrollHeight;
              }, 100);
            }
            if (data.result == "" || code != 0) {
              Toast(`二级引导获取文案失败\ncode${code} ${msg}`);
              setTimeout(() => {
                dialogData.value.push({
                  content: choice,
                  isUser: true,
                });
              }, 100);
              setTimeout(() => {
                contentRef.value.scrollTop = contentRef.value.scrollHeight;
              }, 100);
              setTimeout(() => {
                dialogData.value.push({
                  content: "二级引导选项获取文案失败" + data.msg,
                  errorMsg: true,
                });
              }, 100);
              setTimeout(() => {
                contentRef.value.scrollTop = contentRef.value.scrollHeight;
              }, 100);
            }
          }, 100);
        }
        return;
    }
  }
  if (remainTimes.value < 1) {
    showDialog.value = true; // 用户可用当前权益的次数不足
    return;
  }
  // 没有children的一级引导(其实是脏数据，生产可能不存在这种情况)重新生成部分
  if (regenerate && !staticGuidence.includes(regenerate) && firstClassGuidance.value.find((item) => item == regenerate)) {
    setTimeout(async () => {
      const { code, data } = await reqGuideResult(userId.value, 9, regenerate, historyPromptId.value);
      if (code == 0 && data.result) {
        promptId.value = data.result.promptId;
        dialogData.value.push({
          content: "重新生成",
          isUser: true,
        });
        setTimeout(() => {
          contentRef.value.scrollTop = contentRef.value.scrollHeight;
        }, 100);
        dialogData.value.push({
          content: "",
          loading: true,
        });
        setTimeout(() => {
          contentRef.value.scrollTop = contentRef.value.scrollHeight;
        }, 100);
        polling(getGenerateResult); // 获取promptId，轮训文案生成接口
      }
      if ((data.result = "" || code != 0)) {
        Toast(`一级引导文案重新生成失败\ncode${code} ${data.msg}`);
        setTimeout(() => {
          contentRef.value.scrollTop = contentRef.value.scrollHeight;
        }, 100);
      }
    }, 100);
  }
  // 二级引导重新生成部分(分为已生成文案的重新生成，和文案生成失败的重新生成)
  if (regenerate && !staticGuidence.includes(regenerate) && !firstClassGuidance.value.includes(regenerate) && isNameInOriginGuidance(regenerate)) {
    if (!historyPromptId.value) {
      // Toast('获取不到历史PromptId 无法重新生成')
      setTimeout(async () => {
        const { code, data, msg } = await reqGuideResult(userId.value, 7, regenerate);
        if (code == 0 && data.result) {
          promptId.value = data.result.promptId;
          dialogData.value.push({
            content: "重新生成",
            isUser: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
          dialogData.value.push({
            content: "",
            loading: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
          polling(getGenerateResult); // 获取promptId，轮训文案生成接口
        }
        if (!data.result || code != 0) {
          Toast(`二级引导重新生成文案失败\ncode${data.msg}`);
        }
      }, 100);
    } else {
      setTimeout(async () => {
        const { code, data, msg } = await reqGuideResult(userId.value, 9, regenerate, historyPromptId.value);
        if (code == 0 && data.result) {
          promptId.value = data.result.promptId;
          dialogData.value.push({
            content: "重新生成",
            isUser: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
          dialogData.value.push({
            content: "",
            loading: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
          polling(getGenerateResult); // 获取promptId，轮训文案生成接口
        }
        if (code != 0) {
          Toast(`二级引导重新生成文案失败\ncode${code} ${msg}`);
        }
      }, 100);
    }
  }
  // 自由对话部分
  if (message.value && !choice) {
    userMessage.value = message.value;
    message.value = "";
    setTimeout(() => {
      dialogData.value.push({
        content: userMessage.value,
        isUser: true,
      });
    }, 100);
    setTimeout(() => {
      contentRef.value.scrollTop = contentRef.value.scrollHeight; // 获取焦点后会话部分滚动到最底部
    }, 100);
    setTimeout(() => {
      dialogData.value.push({
        content: "",
        loading: true,
      });
    }, 100);
    setTimeout(() => {
      contentRef.value.scrollTop = contentRef.value.scrollHeight;
    }, 100);

    // 调回答的接口，如果拿到回答的那句，先pop掉loading然后再push
    setTimeout(async () => {
      let scene = ref(4);
      console.log(">>>> userMessage.value >>>>", userMessage.value);
      console.log(">>>> inputContent >>>>", inputContent);
      if (userMessage.value == inputContent) {
        console.log("智能选题跳转内容发送！");
        scene.value = pageType.value == 1 ? 10 : 12;
      }
      const { code, data, msg } = await reqFreeTalk(userId.value, userMessage.value, scene.value, "", contentList.value);
      if (code == 0 && data.result) {
        switch (data.result.submitStatus) {
          case 0: // 成功
            promptId.value = data.result.promptId;
            polling(getGenerateResult); // 获取promptId，轮训文案生成接口
            break;
          case 1: // 请求失败
            Toast("获取promptId失败");
            break;
          case 2: // 超过并发
            dialogData.value.pop();
            dialogData.value.push({
              content: "超过并发",
              errorMsg: true,
            });
            break;
        }
      }
      if (code != 0) {
        Toast(`自由会话异常\ncode${code} ${msg}`);
        dialogData.value.pop();
        dialogData.value.pop();
        dialogData.value.push({
          content: userMessage.value,
          isUser: true,
          isError: true,
        });
      }
    }, 100);
  }
  // 自由对话感叹号重新发送
  if (resendMsg && !choice) {
    console.log(">>>> resendMsg >>>>", resendMsg);
    dialogData.value[resendIndex.value].isError = false;
    setTimeout(() => {
      dialogData.value.push({
        content: "",
        loading: true,
      });
    }, 100);
    setTimeout(() => {
      contentRef.value.scrollTop = contentRef.value.scrollHeight;
    }, 100);
    setTimeout(async () => {
      let scene = ref(4);
      console.log(">>>> userMessage.value >>>>", userMessage.value);
      console.log(">>>> inputContent >>>>", inputContent);
      if (userMessage.value == inputContent) {
        console.log("智能选题跳转内容发送！");
        scene.value = pageType.value == 1 ? 10 : 12;
      }
      const { code, data, msg } = await reqFreeTalk(userId.value, userMessage.value, scene.value, "", contentList.value);
      if (code == 0 && data.result) {
        dialogData.value.filter((item) => item.content === resendMsg);
        switch (data.result.submitStatus) {
          case 0: // 成功
            promptId.value = data.result.promptId;
            polling(getGenerateResult); // 获取promptId，轮训文案生成接口
            break;
          case 1: // 请求失败
            dialogData.value[resendIndex.value].isError = true;
            Toast("获取promptId失败");
            break;
          case 2: // 超过并发
            dialogData.value[resendIndex.value].isError = true;
            dialogData.value.pop();
            dialogData.value.push({
              content: "超过并发",
              errorMsg: true,
            });
            break;
        }
      }
      if (code != 0) {
        dialogData.value[resendIndex.value].isError = true;
        Toast(`reSendMsg error\ncode${code} ${msg}`);
        dialogData.value.pop();
      }
    }, 100);
  }
  // 自由对话重新生成
  if (regenerate && !isNameInOriginGuidance(regenerate) && !staticGuidence.includes(regenerate) && !choice) {
    setTimeout(async () => {
      let scene = ref(6);
      console.log(">>>> userMessage.value >>>>", userMessage.value);
      console.log(">>>> inputContent >>>>", inputContent);
      if (regenerate == inputContent) {
        console.log("智能选题跳转内容重新发送！");
        scene.value = pageType.value == 1 ? 11 : 13;
      }
      const { code, data, msg } = await reqFreeTalk(userId.value, userMessage.value, scene.value, promptId.value, "");
      if (code == 0 && data.result) {
        switch (data.result.submitStatus) {
          case 0: // 成功
            promptId.value = data.result.promptId;
            dialogData.value.push({
              content: "重新生成",
              isUser: true,
            });
            setTimeout(() => {
              contentRef.value.scrollTop = contentRef.value.scrollHeight;
            }, 100);
            dialogData.value.push({
              content: "",
              loading: true,
            });
            setTimeout(() => {
              contentRef.value.scrollTop = contentRef.value.scrollHeight;
            }, 100);
            polling(getGenerateResult); // 获取新的promptId，轮训文案生成接口
            break;
          case 1: // 请求失败
            Toast("获取promptId失败");
            break;
          case 2: // 超过并发
            dialogData.value.pop();
            dialogData.value.push({
              content: "超过并发",
              errorMsg: true,
            });
            break;
        }
      }
      if (code != 0) {
        Toast(`重新生成失败\n${msg}`);
      }
    }, 100);
  }
  placeholder.value = "描述您想写的主题生成脚本";
};
// 重新发送
const resendIndex = ref();
const doResend = (resendMsg, index) => {
  if (isAnswering.value) {
    Toast("正在回答中，请稍后发送");
  } else {
    resendIndex.value = index;
    sendMsg("", resendMsg);
  }
};

// 监听是否正在生成文本
const isAnswering = ref(false);
watch(dialogData.value, (newVal) => {
  if (newVal.find((item) => item.loading == true)) {
    isAnswering.value = true;
  } else {
    isAnswering.value = false;
  }
});

// 每日推荐部分
const dailyRecommend = ref({});
const promptId = ref("");
// 获取每日推荐的promptId 轮询文案生成接口
const getDailyRecommend = async (scence = 1) => {
  const { code, data, msg } = await reqDailyRecommend(userId.value, scence);
  if (code == 0 && data.result) {
    switch (data.result.submitStatus) {
      case 0:
        promptId.value = data.result.promptId;
        if (scence == 3) {
          dialogData.value.push({
            content: "重新生成",
            isUser: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
          dialogData.value.push({
            content: "",
            loading: true,
          });
          setTimeout(() => {
            contentRef.value.scrollTop = contentRef.value.scrollHeight;
          }, 100);
          polling(getRegenerateRecommend);
        } else {
          polling(getRecommendResult);
        }
        break;
      case 1:
      case 3:
        Toast("参数错误或数据保存失败");
        break;
      case 2:
        Toast("超出并发");
        break;
    }
  }
  if (data.code == 500) {
    Toast(data.msg + " 请重试");
  }
  if (code != 0) {
    clearInterval(timer);
    Toast(`获取每日推荐失败\ncode${code} ${msg}`);
  }
};

// 挂载时 每日推荐结果
const getRecommendResult = async () => {
  pageLoading.value = true;
  const { code, data, msg } = await reqBotResult(userId.value, promptId.value);
  if (code == 0 && data.result) {
    switch (data.result.generationStatus) {
      case 0:
        clearInterval(timer);
        pageLoading.value = false;
        dailyRecommend.value.title = data.result.title;
        dailyRecommend.value.screenPlay = data.result.body;
        dailyRecommend.value.promptId = promptId.value;
        break;
      case 2:
      case 3:
      case 4: // 都属于失败，可以不再轮训
        clearInterval(timer);
        pageLoading.value = false;
        dialogData.value.pop();
        dialogData.value.push({
          content: "生成文案失败",
          errorMsg: true,
        });
        break;
    }
  }
  if (code != 0) {
    clearInterval(timer);
    pageLoading.value = false;
    Toast(`数据或网络异常\ncode${code} ${msg}`); // 感叹号
  }
};

// 文案会话内容结构
const content = {
  title: "",
  screenPlay: "",
  promptId: "",
};

// 重新生成每日推荐
const getRegenerateRecommend = async () => {
  const { code, data, msg } = await reqBotResult(userId.value, promptId.value);
  if (code == 0 && data.result) {
    switch (data.result.generationStatus) {
      case 0:
        clearInterval(timer);
        content.title = data.result.title;
        content.screenPlay = data.result.body;
        content.promptId = promptId.value;
        dialogData.value.pop();
        dialogData.value.push({
          content: content,
          isDailyRecommend: true,
        });
        setTimeout(() => {
          contentRef.value.scrollTop = contentRef.value.scrollHeight; // 获取焦点后会话部分滚动到最底部
        }, 100);
        await getPointsInfo(userId.value); // 每日推荐重新生成成功会消耗一次权益
        break;
      case 2:
      case 3:
      case 4: // 都属于失败，可以不再轮训
        clearInterval(timer);
        pageLoading.value = false;
        dialogData.value.pop();
        dialogData.value.push({
          content: "生成文案失败",
          errorMsg: true,
        });
        break;
    }
  }
  if (code != 0) {
    clearInterval(timer);
    pageLoading.value = false;
    Toast(`数据或网络异常\ncode${code} ${msg}`); // 感叹号
  }
};

// 文案生成结果（通过引导选项）
const getGenerateResult = async () => {
  const { code, data, msg } = await reqBotResult(userId.value, promptId.value);
  if (code == 0 && data.result) {
    switch (data.result.generationStatus) {
      case 0:
        clearInterval(timer);
        content.title = data.result.title;
        content.screenPlay = data.result.body;
        content.promptId = promptId.value;
        dialogData.value.pop();
        dialogData.value.push({
          content: content,
          isDailyRecommend: true,
        });
        setTimeout(() => {
          contentRef.value.scrollTop = contentRef.value.scrollHeight; // 获取焦点后会话部分滚动到最底部
        }, 100);
        await getPointsInfo(userId.value); // 文案生成成功会消耗一次权益
        break;
      case 2:
      case 3:
      case 4: // 都属于失败，可以不再轮训
        clearInterval(timer);
        if (resendIndex.value) {
          dialogData.value[resendIndex.value].isError = true;
        }
        dialogData.value.pop();
        dialogData.value.push({
          content: "生成文案失败",
          errorMsg: true,
        });
        break;
    }
  }
  if (code != 0) {
    clearInterval(timer);
    if (resendIndex.value) {
      dialogData.value[resendIndex.value].isError = true;
    }
    dialogData.value.pop();
    dialogData.value.push({
      content: "数据或网络异常，生成文案失败",
      errorMsg: true,
    });
    Toast(`数据或网络异常\ncode${code} ${msg}`); // 感叹号
  }
};

// 重新生成
const isRetry = ref(false);
const historyPromptId = ref("");
const doRetry = (Id, title, content = "") => {
  if (remainTimes.value < 1) {
    showDialog.value = true; // 用户可用当前权益的次数不足
    return;
  }
  if (isAnswering.value) {
    Toast("正在回答中，请稍后发送");
    return;
  } else {
    historyPromptId.value = Id;
    isRetry.value = true;
    if (title == "原创内容每日推荐") {
      getDailyRecommend(3);
    }
    if (title == "为您生成文案如下") {
      freeTalkRetry(content);
    }
  }
};

const rotating = ref(false);
const freeTalkRetry = (v) => {
  console.log(">>>> 获取要重新生成的内容 >>>>", v);
  rotating.value = true;
  setTimeout(() => {
    rotating.value = false;
  }, 800);
  sendMsg("", "", v);
};

// 递归判断用户会话是否属于树级结构的引导选项
const isNameInOriginGuidance = (str, array = originGuidance.value) => {
  for (const item of array) {
    if (item.name === str) {
      return true;
    }
    if (item.children && item.children.length > 0) {
      if (isNameInOriginGuidance(str, item.children)) {
        return true;
      }
    }
  }
  return false;
};

// 焦点相关事件
const message = ref("");
const getFocus = ref(false);
const touchCoversation = () => {
  setTimeout(() => {
    textareaRef.value.blur(); // 失去焦点
  }, 100);
};
const onInput = () => {
  textareaRef.value.focus(); // 获取焦点
  getFocus.value = true;
  contentRef.value.scrollTop = contentRef.value.scrollHeight; // 获取焦点后会话部分滚动到最底部
};
let keyboardShow = ref(false);
const onFocus = () => {
  if (isAndroid()) {
    keyboardShow.value = true;
  }
  setTimeout(() => {
    window.addEventListener("scroll", touchCoversation); // 软键盘弹起后，监听页面的滚动，如果有就失去焦点收起
  }, 100);
};
const onBlur = () => {
  if (isAndroid()) {
    setTimeout(() => {
      keyboardShow.value = false;
    }, 100);
  }
  window.removeEventListener("scroll", touchCoversation);
  setTimeout(() => {
    getFocus.value = false;
  }, 100);
};

// placeholder部分（组件自带的会存在顶不起软键盘的bug）
const placeholder = ref("描述您想写的主题生成脚本");
const handleInput = (e) => {
  if (e.target.value) {
    placeholder.value = "";
  } else {
    placeholder.value = "描述您想写的主题生成脚本";
  }
};

// 设置轮训 参数名为要轮训的函数
let timer;
const polling = (v) => {
  if (promptId.value) {
    timer = setInterval(v, 1000);
  } else {
    Toast("promptId为空 获取文案失败");
    // 正常接下来应该走重新生成的逻辑
  }
};

// 提示分割线的显隐
const showHistory = ref(false);
const getShowHistoryTip = async () => {
  let scene = pageType.value == 1 || 2 ? 'smartTopic' : '';   //  设置获取历史记录的场景
  const { code, data, msg } = await reqSessionHistory(userId.value, 1, endTime.value, scene);
  if (code == 0 && data.result) {
    if (data.result.history.length !== 0) {
      showHistory.value = true;
    }
  } else {
    Toast(`获取聊天记录失败\ncode${code} ${msg}`);
  }
};

// 判断客户端机型
const iosClient = ref(true);
if (isAndroid()) {
  iosClient.value = false;
}

// 获取选题详情跳转过来时画报或跟拍的标识及参数
const pageType = ref(0);
const contentList = ref([]);
const inputContent = getUrlParams("inputContent");
// const wordNumber = inputContent.match(/[\u4E00-\u9FA5]/g)?.length;
// console.log(">>>> 选题文字个数 >>>>", wordNumber);
// if (wordNumber > 1600) {
//   inputContent = "为我生成一篇短视频文案";
// }
pageType.value = getUrlParams("type");
contentList.value = JSON.parse(window.sessionStorage.getItem("CONTENTLIST"));
console.log(">>>> pageType >>>>", pageType, ">>>> inputContent >>>>", inputContent, ">>>> contentList >>>>", contentList.value);
if (inputContent) {
  message.value = inputContent;
  placeholder.value = "";
}
const changePageType = (e) => {
  console.log("e", e);
  pageType.value = e == 1 ? "1" : "2";
};

// 挂载页面
const userId = ref("");
const endTime = ref("");
onMounted(async () => {
  const { agentNo } = await getAccountInfos();
  userId.value = agentNo;
  endTime.value = new Date().getTime();
  getDailyRecommend(); // 获取每日推荐
  getShowHistoryTip(); // 是否显示下拉历史记录提示分割线
  getPointsInfo(); // 获取用户权益信息
});
</script>

<style lang="less" scoped>
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.retry {
  font-family: PingFangSC-Regular;
  font-size: 11px;
  color: rgba(0, 0, 0, 0.6);
  letter-spacing: 0;
  font-weight: 400;
  height: 10px;
  display: flex;
  align-items: center;
  margin-left: 10px;
  margin-bottom: 10px;

  .retry-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    background: url("../asset/icons/icon_refresh@3x.png") no-repeat;
    background-size: 100% 100% !important;
    margin-right: 3px;
  }

  .rotate-icon {
    animation: rotate 2s linear;
  }
}

.loading-box {
  width: 50px;
  height: 50px;
  background-color: #000;
  border-radius: 2px;
  opacity: 0.7;
  position: fixed;
  z-index: 999;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.history {
  padding: 0px 15px 15px 15px;

  span {
    transform: rotate(17deg);
    border: 1px solid rgba(84, 139, 246, 1);
  }

  .chat-messages {
    display: flex;
    flex-direction: column;
    flex: 1;
    position: relative;

    .ask-message {
      .bubble;
      align-self: flex-end;
      opacity: 0.8;
      font-family: PingFangSC-Regular;
      font-size: 15px;
      color: #ffffff;
      text-align: justify;
      font-weight: 400;
      border-radius: 12px 12px 2px 12px;
      background-image: linear-gradient(270deg, #525eea 0%, #3d75df 100%);
    }

    .answer-message {
      .bubble;
      align-self: flex-start;
      font-family: PingFangSC-Regular;
      font-size: 15px;
      color: #000000;
      line-height: 22px;
      font-weight: 400;
      background: #f7f7f7;
      border-radius: 12px 12px 12px 2px;
    }

    .ai-loading {
      width: 40px;
      height: 40px;
      // margin: -10px -8px -15px -8px;
    }

    .error-icon {
      position: absolute;
      left: -25px;
      width: 20px;
      height: 20px;
    }

    .none {
      display: none;
    }
  }
}

:deep(.van-dialog__content) {
  .message {
    width: 225px;
    margin: 0 auto;
    padding: 20px 0;
  }
}

.dialog-options {
  padding: 0 15px 15px 15px;
}

.bubble {
  position: relative;
  padding: 15px;
}

.container {
  position: relative;
  height: 100%;

  .right {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    right: 15px;
    top: 50%;
    transform: translateY(-50%);
    font-family: PingFangSC-Medium;
    font-size: 14px;
    color: #000000;
    text-align: center;
    font-weight: 500;
    text-decoration: underline;
  }

  .content {
    width: 100%;
    overflow: scroll;
    -webkit-overflow-scroll: touch;
    background-color: #f7f7f7;
    background: transparent;
    transition: all 5s linear;

    .coversation {
      width: 100%;
      height: 100%;
      padding: 15px 15px 30px 15px;
      overflow-y: scroll;
      transition: all 5s linear;

      .chat-messages {
        display: flex;
        flex-direction: column;
        flex: 1;
        position: relative;

        .generate-text {
          margin-top: -15px;
          background: #fff;
        }

        .ask-message {
          .bubble;
          max-width: 315px;
          padding: 15px !important;
          align-self: flex-end;
          margin-top: 15px;
          margin-bottom: 15px;
          opacity: 0.8;
          font-family: PingFangSC-Regular;
          font-size: 15px;
          color: #ffffff;
          text-align: justify;
          font-weight: 400;
          border-radius: 12px 12px 2px 12px;
          background-image: linear-gradient(270deg, #525eea 0%, #3d75df 100%);
        }

        .answer-message {
          .bubble;
          margin-top: 15px;
          align-self: flex-start;
          font-family: PingFangSC-Regular;
          font-size: 15px;
          color: #000000;
          line-height: 22px;
          font-weight: 400;
          background: #f7f7f7;
          border-radius: 12px 12px 12px 2px;
        }

        .ai-loading {
          width: 40px;
          height: 40px;
          margin: -10px -8px -15px -8px;
        }

        .error-icon {
          position: absolute;
          left: -25px;
          width: 20px;
          height: 20px;
        }

        .none {
          display: none;
        }
      }
    }
  }

  .input-area {
    width: calc(100vw - 30px);
    height: 60px;
    // height: 100px;
    box-sizing: content-box;
    padding-bottom: 30px;
    position: absolute;
    bottom: 0px;
    background: #ffffff;
    padding-left: 15px;
    padding-right: 15px;

    &.keyboard-show {
      padding-bottom: 85%;
    }

    .input-wrapper {
      width: calc(100vw - 30px);
      margin-top: 15px;
      display: flex;
      align-items: center;
      // flex-wrap: wrap;

      .placeholder {
        position: absolute;
        left: 30px;
        // top: 66px;
        opacity: 0.6;
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #272930;
        font-weight: 400;
        pointer-events: none; // 点击穿透 防止标签占位不方便粘贴
      }

      :deep(.van-cell) {
        padding: 0;

        .van-field__body {
          min-height: 40px;
          max-height: 70px;
          background: #f4f5f7;
          padding-left: 12px;
          padding-right: 5px;
          border-radius: 20px;
          overflow-y: scroll;
          overflow-x: hidden;

          textarea {
            min-height: 40px;
            max-height: 70px;
            padding-top: 8px;
            -ms-overflow-style: none;
            scrollbar-width: none;

            &::-webkit-scrollbar {
              display: none;
            }
          }
        }
      }
    }

    .voice {
      display: inline-block;
      width: 32px;
      height: 32px;
      background: url("../asset/icons/icon_voice@3x.png") no-repeat;
      background-size: 100% 100% !important;
      position: absolute;
      right: 15px;
      top: 19px;
    }

    .send {
      display: inline-block;
      width: 32px;
      height: 32px;
      background: url("../asset/icons/icon_send2@3x.png") no-repeat;
      background-size: 100% 100% !important;
      position: absolute;
      right: 25px;
      // top: 59px;
      top: 19px;
    }
  }
}
</style>
